<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>倒计时</title>
</head>
<body>
    <label for="datetime">选择日期和时间</label>
    <input type="datetime-local" id="datetime"/>
    <div id="countdown"></div>
<script>
    //获取时间选择器
    let datetime=document.querySelector('#datetime');
    //获取显示倒计时的区域
    let countdown=document.querySelector('#countdown');
    let $timer;
    //给日期选择器绑定一个值改变事件
    datetime.addEventListener('change',(event)=>{
        if($timer)clearInterval($timer)
        //当选择了新的日期之后获取最新的日期
        const datetimeValue = event.target.value;
        //转成日期对象
        const targetDatetime = new Date(datetimeValue);
        //开启一个计时器，每隔一秒钟执行一个方法
        $timer = setInterval(()=>{
            updateCountdown(targetDatetime);//更新倒计时
        },1000);
    });
    function updateCountdown(targetDatetime){
        let xhr = new XMLHttpRequest();
        xhr.open('GET','/',true);
        xhr.onload = ()=>{
            let serverDateTime = new Date(xhr.getResponseHeader('Date'));
            const diff = targetDatetime-serverDateTime;
            if(diff>0){
                let seconds = Math.floor((diff/1000)%60);
                let minutes = Math.floor((diff/(1000*60))%60);
                let hours = Math.floor((diff/(1000*60*60))%24);
                let days = Math.floor((diff/(1000*60*60*24))%30.44);
                let months = Math.floor((diff/(1000*60*60*24*30.44))%12);
                let years = Math.floor(diff/(1000*60*60*24*365));
                let desc ='';
                if(years){
                    desc+=`${years}年`;
                }
                if(months){
                    desc+=`${months}月`;
                }
                if(days){
                    desc+=`${days}日`;
                }
                if(hours){
                    desc+=`${hours}时`;
                }
                if(minutes){
                    desc+=`${minutes}分`;
                }
                if(seconds){
                    desc+=`${seconds}秒`;
                }
                countdown.innerHTML = `距离截止日期还有${desc}`;
            }
           
        }
        xhr.send();
    }
</script>    
</body>
</html>